package com.spice.im;


import org.jivesoftware.smack.util.StringUtils;




import com.example.android.bitmapfun.util.ObjectCache;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.BeemService;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.utils.BeemConnectivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AdvancedSearch extends Activity implements OnClickListener{
	
    private static final Intent SERVICE_INTENT = new Intent();

    static {
    	SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
    }
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    
    private Context mContext;
    
    private final ServiceConnection mServConn = new BeemServiceConnection();
    
//	protected TextView mSearchtype;
//	protected TextView mAges;
//	protected TextView mGenders;
//	protected TextView mDistances;
//	protected CheckedTextView mOnline;
	private Button mSearchbtn;
    String searchkey;
//    String searchtype;
//    String ages;
//    String genders;
//    String distances;
//    String online;
    
    private HeaderLayout mHeaderLayout;
    
    private String myheadimg = "";
    private String myusername = "";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.search);
        
    	myheadimg = getIntent().getStringExtra("myheadimg");
    	if(myheadimg==null || myheadimg.equalsIgnoreCase("null"))
    		myheadimg = "";
    	myusername = getIntent().getStringExtra("myusername");
    	if(myusername==null || myusername.equalsIgnoreCase("null"))
    		myusername = "";
        
		mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
//		mHeaderLayout.init(HeaderStyle.DEFAULT_TITLE);
		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//		mHeaderLayout.setDefaultTitle("高级查找", null);
		mHeaderLayout.setTitleRightImageButton("高级查找", null,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
//        mSearchtype = (TextView) findViewById(R.id.searchtype);
//		mAges = (TextView) findViewById(R.id.ages);
//		mGenders = (TextView) findViewById(R.id.genders);
//		mDistances = (TextView) findViewById(R.id.distances);
//		mOnline = (CheckedTextView) findViewById(R.id.online);
		
		mSearchbtn = (Button) findViewById(R.id.searchbtn);
//		mSearchtype.setOnClickListener(this);
//		mAges.setOnClickListener(this);
//		mGenders.setOnClickListener(this);
//		mDistances.setOnClickListener(this);
//		mOnline.setOnClickListener(this);
		mSearchbtn.setOnClickListener(this);
		SpiceApplication.getInstance().addActivity(this);
    }
    
	public void onClick(View v) {
		switch (v.getId()) {
//		case R.id.searchtype:
//			showSearchtypeDialog();
//			break;
//		case R.id.ages:
//			showAgesDialog();
//			break;
//
//		case R.id.genders:
//			showGendersDialog();
//			break;
//			
//		case R.id.distances:
//			showDistancesDialog();
//			break;
//			
//		case R.id.online:
//			mOnline.toggle();
//			break;
		case R.id.searchbtn:
			searchkey = getWidgetText(R.id.searchkey);
			if (searchkey == null || searchkey.equalsIgnoreCase("null") || searchkey.length()==0) {
				showCustomToast("请输入昵称（姓名）或账号（用户名）");
			} else{
//			searchtype = mSearchtype.getText().toString();
//			//        <item>找人(0)</item>
////	        <item>找群(1)</item>
//			if(searchtype.endsWith("0)"))
//				searchtype = "0";//
//			else
//				searchtype = "1";
////	        <item>不限(0)</item>
////	        <item>16–22岁(1)</item>
////	        <item>23–30岁(2)</item>
////	        <item>31–40岁(3)</item>
////	        <item>40岁以上(4)</item>
//			ages = mAges.getText().toString();
//			if(ages.endsWith("0)"))
//				ages = "0";
//			else if(ages.endsWith("1)"))
//				ages = "1";
//			else if(ages.endsWith("2)"))
//				ages = "2";
//			else if(ages.endsWith("3)"))
//				ages = "3";
//			else if(ages.endsWith("4)"))
//				ages = "4";
////	        <item>不限(0)</item>
////	        <item>1男(1)</item>
////	        <item>2女(2)</item>
//			genders = mGenders.getText().toString();
//			if(genders.endsWith("0)"))
//				genders = "0";
//			else if(genders.endsWith("1)"))
//				genders = "1";
//			else if(genders.endsWith("2)"))
//				genders = "2";
//		    distances = mDistances.getText().toString();
//		    online = mOnline.getText().toString();
		    
				
				
				if(ObjectCache.getStatus("isConnected", getApplicationContext())){
						if(BeemConnectivity.isConnected(getApplicationContext())){
						try {
					    	if(mXmppFacade!=null){
						    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
										&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
										&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
						    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
						    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
	//									&& mXmppFacade.getXmppConnectionAdapter().login()//注意，第三方登陆login之前，需要调用框架本身的auth接口
										&& mXmppFacade.getXmppConnectionAdapter().getJID()!=null
										&& mXmppFacade.getXmppConnectionAdapter().getJID().length()!=0
										&& !mXmppFacade.getXmppConnectionAdapter().getJID().equalsIgnoreCase("null")
						    			){
					
				Intent intent = new Intent(AdvancedSearch.this,OtherProfileActivity.class);//AdvancedSearchResPullRefListActivity
				 
				intent.putExtra("searchkey", searchkey);
	//			intent.putExtra("searchtype", searchtype);
	//			intent.putExtra("ages", ages);
	//			intent.putExtra("genders", genders);
	//			intent.putExtra("distances", distances);
	//			intent.putExtra("online", online);
		    	intent.putExtra("myheadimg", myheadimg);
		    	intent.putExtra("myusername",myusername);
				startActivity(intent); 
				finish();
				
						    	}else{
						    		errorType = 1;//客户端网络是ok的，但是服务器可能宕机了
						    		showCustomToast(errorMsg[errorType]);
						    	}
					    	}else{
					    		errorType = 2;
					    		showCustomToast(errorMsg[errorType]);
					    	}
						}catch(Exception e){
							errorType = 3;
							showCustomToast(errorMsg[errorType]);
						}
					}else{
						errorType = 4;
						showCustomToast(errorMsg[errorType]);
					}
				}else{
					if(BeemConnectivity.isConnected(getApplicationContext()))
		    			errorType = 6;
		    		else
		    			errorType = 4;
					showCustomToast(errorMsg[errorType]);
				}
			
			break;
			}
		}
	}
	
	
	
    /**
     * Get the text of a widget.
     * @param id the id of the widget.
     * @return the text of the widget.
     */
    private String getWidgetText(int id) {
		EditText widget = (EditText) this.findViewById(id);
		return widget.getText().toString();
    }
    
//    protected void showSearchtypeDialog() {
//		final String[] items = this.getResources().getStringArray(
//				R.array.searchtype);
//		new AlertDialog.Builder(this)
//				.setTitle("选择查找类别")
//				.setSingleChoiceItems(items, 0,
//						new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								mSearchtype.setText(items[which]);
//								dialog.dismiss();
//							}
//						}).create().show();
//
//	}
//    protected void showAgesDialog() {
//		final String[] items = this.getResources().getStringArray(
//				R.array.ages);
//		new AlertDialog.Builder(this)
//				.setTitle("选择年龄")
//				.setSingleChoiceItems(items, 0,
//						new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								mAges.setText(items[which]);
//								dialog.dismiss();
//							}
//						}).create().show();
//
//	}

//	protected void showGendersDialog() {
//		final String[] items = this.getResources().getStringArray(
//				R.array.genders);
//		new AlertDialog.Builder(this)
//				.setTitle("选择性别")
//				.setSingleChoiceItems(items, 0,
//						new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								mGenders.setText(items[which]);
//								dialog.dismiss();
//							}
//						}).create().show();
//
//	}

//	protected void showDistancesDialog() {
//		final String[] items = this.getResources().getStringArray(
//				R.array.distances);
//		new AlertDialog.Builder(this)
//				.setTitle("选择距离")
//				.setSingleChoiceItems(items, 0,
//						new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								mDistances.setText(items[which]);
//								dialog.dismiss();
//							}
//						}).create().show();
//
//	}
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
			startActivity(new Intent(AdvancedSearch.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			AdvancedSearch.this.finish();
		}
	}
	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"已登录",
			"未登录",
			"请求异常,稍候重试!"};
	private int errorType = 5;
	
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(AdvancedSearch.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(AdvancedSearch.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
	
    private class BeemServiceConnection implements ServiceConnection {

		/**
		 * constructor.
		 */
		public BeemServiceConnection() {
		}
	
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;//20130804 added by allen
		    }
		}
	
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
		    mXmppFacade = null;
		    mBinded = false;//20130804 added by allen
		}
    }
    
    @Override
    protected void onResume() {
		super.onResume();
		if (!mBinded){
			Intent intent = new Intent(this, BeemService.class);
//			intent.putExtra("uFlag_startfromsetting", "1");
			mBinded = bindService(intent, mServConn, BIND_AUTO_CREATE);
		}
    }
    @Override
    protected void onPause() {
		super.onPause();
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
		super.onDestroy();
		if (mBinded) {
			unbindService(mServConn);
			mBinded = false;
		}
    }
}
